<template>
    <div class="main clearfix">
        <!--发布商品-->
        <div class="main-comments clearfix">
            <h2 class="title">发布商品</h2>
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="商品名称" prop="goodName">
                    <el-input v-model="ruleForm.goodName" style="width:300px;"></el-input>
                </el-form-item>
                <el-form-item label="商品类别" prop="typeName">
                    <el-select v-model="ruleForm.typeName" placeholder="请选择商品类别">
                        <el-option :label="select.typeName" :value="select.typeName" v-for="(select,index) in selectList" :key="select.typeId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品单价" prop="unitPrice">
                    <el-input v-model="ruleForm.unitPrice" style="width:200px;" placeholder="单位(元)"></el-input>
                </el-form-item>
                <el-form-item label="商品数量" prop="inventory">
                    <el-input v-model.number="ruleForm.inventory" style="width:200px;"></el-input>
                </el-form-item>
                <el-form-item label="商品描述" prop="description">
                    <el-input type="textarea" v-model="ruleForm.description" style="width:500px;" resize="none" :autosize="{ minRows: 2, maxRows: 6 }"></el-input>
                </el-form-item>

                <el-upload class="upload-demo" ref="upload" drag :auto-upload="false" :limit="maxFileNums" style="margin-left:100px;
                width:500px;
                margin-bottom:50px;" action="#" :before-remove="beforeRemove" :on-exceed="onExceed" :before-upload="beforeAvatarUpload" :http-request="handleFileUpload">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text" style>
                        将文件拖到此处，或
                        <em>点击上传</em>
                    </div>
                    <div class="el-upload__tip" slot="tip">只能上传jpg/png/jpeg/bmp/gif/pjpeg/x-png文件，且不超过1MB</div>
                </el-upload>
                <el-form-item>
                    <el-button type="primary" @click="submitForm">立即发布</el-button>
                    <el-button @click="resetForm('ruleForm')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!--已发布商品-->
        <div class="uc-box uc-main-box">
            <div class="uc-content-box order-list-box">
                <div class="box-hd">
                    <h1 class="title">我发布的</h1>
                    <div class="more clearfix">
                        <div class="search-form clearfix">
                            <input type="search" name="keywords" autocomplete="off" placeholder="输入商品名称" class="search-text" v-model="params.keyword" />
                            <div class="search-btn" @click="getData">
                                <i class="icon-sousuo iconfont"></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="box-bd">
                    <div>
                        <ul class="order-list">
                            <li class="research-item clearfix" v-for="(publicItem,index) in userPublicList" :key="publicItem.goodsId">
                                <router-link :to="`/detail/${publicItem.goodsId}`" class="link clearfix">
                                    <img v-lazy="publicItem.picture" />
                                    <ul class="information clearfix">
                                        <li class="price-wrapper clearfix">
                                            <i class="iconfont icon-renminbi1688"></i>
                                            <div class="price">{{ publicItem.unitPrice.toFixed(2) }}</div>
                                        </li>

                                        <li class="seller-wrapper clearfix">
                                            <div class="seller">{{ publicItem.goodsName }}</div>
                                        </li>

                                        <li class="describe-wrapper clearfix">
                                            <div class="describe">{{ publicItem.description }}</div>
                                        </li>
                                    </ul>
                                    <!-- stop是阻止事件冒泡，但是i本身也是a（router-link）标签的一部分，所以无法阻止 -->
                                    <!-- 而prevent是阻止默认事件，刚刚好可以做到这一点 -->
                                    <el-tooltip class="item" effect="light" content="编辑" placement="bottom-start">
                                        <i class="iconfont icon-bianji" @click.prevent="openEditDialog(publicItem)"></i>
                                    </el-tooltip>
                                </router-link>
                                <div class="mask" v-if="publicItem.status == 0">
                                    <p>商品已下架</p>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="wrapper">
                <el-pagination background layout="prev, pager, next" :total="userPublicTotalNums" class="pagination" style="display: flex;
                    justify-content: center;" :page-size="params.pageSize" @current-change="handleCurrentChange"></el-pagination>
            </div>
        </div>

        <!-- 编辑商品的框 -->
        <el-dialog title="收货地址" :visible.sync="dialogFormVisible" :before-close="handleClose" :close-on-click-modal="false">
            <el-form :model="dialogForm" :rules="rules" ref="dialogForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="商品名称" prop="goodsName">
                    <el-input v-model="dialogForm.goodsName" style="width:300px;"></el-input>
                </el-form-item>
                <el-form-item label="商品类别" prop="typeName">
                    <el-select v-model="dialogForm.typeName" placeholder="请选择商品类别">
                        <el-option :label="select.typeName" :value="select.typeName" v-for="(select,index) in selectList" :key="select.typeId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品单价" prop="unitPrice">
                    <el-input v-model="dialogForm.unitPrice" style="width:200px;" placeholder="单位(元)"></el-input>
                </el-form-item>
                <el-form-item label="商品数量" prop="inventory">
                    <el-input v-model.number="dialogForm.inventory" style="width:200px;"></el-input>
                </el-form-item>
                <el-form-item label="商品描述" prop="description">
                    <el-input type="textarea" v-model="dialogForm.description" style="width:500px;" resize="none" :autosize="{ minRows: 2, maxRows: 6 }"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="deletePublicGoods(dialogForm.goodsId)">下架</el-button>
                <el-button type="primary" @click="checkInfo">修改商品</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    reqSelectList,
    reqPublicGoods,
    reqEditUserPublicGoodsInfo,
    reqDeleteUserPublicGoods,
} from "@/api";
import { mapState } from "vuex";
export default {
    data() {
        return {
            ruleForm: {
                goodName: "",
                typeName: "",
                unitPrice: "",
                inventory: "",
                description: "",
            },
            rules: {
                goodName: [
                    {
                        required: true,
                        message: "请输入商品名称",
                        trigger: "blur",
                    },
                ],
                // 对话框中商品的名称
                goodsName: [
                    {
                        required: true,
                        message: "请输入商品名称",
                        trigger: "blur",
                    },
                ],
                typeName: [
                    {
                        required: true,
                        message: "请选择商品类别",
                        trigger: "change",
                    },
                ],
                unitPrice: [
                    {
                        required: true,
                        message: "输入商品单价",
                        trigger: "blur",
                    },
                    {
                        type: "string",
                        required: true,
                        pattern: /^[0-9]+(\.)?[0-9]*$/,
                        message: "请输入数字内容",
                        trigger: "blur",
                        transform(value) {
                            return String(value).trim();
                        },
                    },
                ],
                inventory: [
                    {
                        required: true,
                        message: "请输入商品库存",
                        trigger: "blur",
                    },
                    {
                        type: "number",
                        message: "请输入数字内容",
                        trigger: "blur",
                    },
                ],
                description: [
                    {
                        required: true,
                        message: "请填写商品描述",
                        trigger: "blur",
                    },
                ],
            },
            // 上传文件的最大数量
            maxFileNums: 1,
            acceptFileClass: [
                "image/jpeg",
                "image/jpg",
                "image/png",
                "image/bmp",
                "image/gif",
                "image/pjpeg",
                "image/x-png",
            ],
            selectList: [],
            params: {
                keyword: "",
                pageNo: 1,
                pageSize: 10,
            },
            dialogFormVisible: false,
            // 修改商品的表单的数据
            dialogForm: {
                goodsId: "",
                goodsName: "",
                typeName: "",
                unitPrice: "",
                inventory: "",
                description: "",
            },
        };
    },
    mounted() {
        this.getSelectList();
        this.getData();
    },
    methods: {
        // 自定义上传形式覆盖原本的el-upload
        handleFileUpload(fileObject) {
            let formData = new FormData();
            let params = Object.assign({}, this.ruleForm);
            params.unitPrice = Number(this.ruleForm.unitPrice);
            console.log(params);
            // 遍历ruleForm来添加键值对
            Object.entries(params).forEach(([key, value]) => {
                formData.append(key, value);
            });
            formData.append("picture", fileObject.file);
            // 定义一个Promise
            let p1 = new Promise(async (resolve, reject) => {
                let result = await reqPublicGoods(formData);
                if (result.code == 200) {
                    resolve("ok");
                } else {
                    reject(result.msg);
                }
            });

            p1.then(
                () => {
                    this.$message.success("发布商品成功");
                    this.getData();
                },
                (error) => {
                    this.$message.error(error);
                }
            );
        },
        // 提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (!valid) {
                    this.$message.warning("输入数据有误，请检查");
                } else {
                    console.log("输入正确");
                    // 调用了这个upload自带的submit之后会跳转到handleFileUpload之中
                    this.$refs.upload.submit();
                }
            });
        },
        // 重置表单
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        // 文件上传超过上限时
        onExceed(files, fileList) {
            // 第一个参数是新添加的列表，第二个参数是已有的文件列表
            this.$message.warning(
                `已超过上传文件的最大数量，最多上传${this.maxFileNums}个文件`
            );
        },
        // 上传图片时做检查
        beforeAvatarUpload(file) {
            const isAccepted = this.acceptFileClass.indexOf(file.type) != -1;
            const isLt1M = file.size / 1024 / 1024 < 1;

            if (!isAccepted) {
                this.$message.error("上传头像图片只能是 JPG 格式!");
                this.$refs.upload.clearFiles();
            }
            if (!isLt1M) {
                this.$message.error("上传头像图片大小不能超过 1MB!");
                this.$refs.upload.clearFiles();
            }
            return isAccepted && isLt1M;
        },
        // 移除图片时的提示
        beforeRemove(file) {
            return this.$msgbox.confirm(`确定移除 ${file.name}？`);
        },
        // 获取分类列表
        async getSelectList() {
            let result = await reqSelectList();
            if (result.code == 200) {
                this.selectList = result.data.goodList;
            } else {
                this.$message.error(result.msg);
            }
        },
        handleCurrentChange(val) {
            this.params.pageNo = val;
            this.getData();
        },
        // 获取用户所发布的商品
        async getData() {
            try {
                await this.$store.dispatch(
                    "user/getUserPublicList",
                    this.params
                );
            } catch (error) {
                this.$message.error(error);
            }
        },
        // 通过右上角关闭修改商品对话框要做的事情
        handleClose(done) {
            done();
        },
        // 打开编辑商品对话框要做的事情
        openEditDialog(goodsInfo) {
            // 先将指定商品的内容传给表单
            Object.entries(this.dialogForm).forEach(([key, value]) => {
                this.dialogForm[key] = goodsInfo[key];
            });
            // 打开对话框
            this.dialogFormVisible = true;
        },
        // 提交商品修改对话框的验证
        checkInfo() {
            this.$refs.dialogForm.validate((valid) => {
                if (!valid) {
                    this.$message.warning("输入数据有误，请检查");
                    return false;
                } else {
                    // 如果验证通过了就提交表单内容
                    this.editGoodsInfo();
                    return true;
                }
            });
        },
        // 修改商品信息
        async editGoodsInfo() {
            this.dialogForm.unitPrice = Number(this.dialogForm.unitPrice);
            let result = await reqEditUserPublicGoodsInfo(this.dialogForm);
            if (result.code == 200) {
                this.$message.success("修改成功！");
                this.$refs.dialogForm.resetFields();
                this.dialogFormVisible = false;
                this.getData();
            } else {
                this.$message.error(result.msg);
            }
        },
        // 下架商品
        deletePublicGoods(goodsId) {
            this.$msgbox.alert("确认下架该商品吗？", "下架商品").then(
                async () => {
                    let result = await reqDeleteUserPublicGoods(goodsId);
                    if (result.code == 200) {
                        this.$message.success("下架成功!");
                        this.$refs.dialogForm.resetFields();
                        this.dialogFormVisible = false;
                        this.getData();
                    } else {
                        this.$message.error(result.msg);
                    }
                },
                () => {
                    console.log("取消");
                }
            );
        },
    },
    computed: {
        ...mapState("user", ["userPublicList", "userPublicTotalNums"]),
    },
};
</script>

<style lang="less" scoped>
/*设置详情页面的样式*/
.main {
    float: left;
    margin-left: 10px;
    margin-bottom: 200px;
}

/*设置评论区的样式*/
.main-comments {
    width: 1040px;
    background-color: rgba(255, 255, 255, 0.8);
}

.title {
    font-size: 18px;
    border-bottom: 1px solid rgb(150, 150, 150);
    padding-bottom: 20px;
    margin: 20px 20px;
}

/*设置商品项目的样式*/
.research-item {
    text-align: center;
    box-sizing: border-box;
    width: 100%;
    margin-bottom: 15px;
    /*此行代码用于在聚焦到对应的项目时产生一个互动动画*/
    transition: all 0.3s;
    position: relative;
    .mask {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background-color: rgba(0, 0, 0, 0.3);
        // 不知道为什么会失效，但是自己开一个html文件不会失效
        // display: table-cell;
        // vertical-align: middle;
        text-align: center;

        p {
            line-height: 160px;
            user-select: none;
            font-size: 45px;
        }
    }
}

.research-item:hover:not(.bottom) {
    transform: translateY(-5px);
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}

.research-item .link {
    color: #333333;
    text-decoration: none;
    display: block;
    box-sizing: border-box;
    height: 160px;
    width: 100%;
    padding: 5px;
    border: 1px solid rgb(215, 223, 232);
    position: relative;
}

.research-item .link > * {
    float: left;
}

/*设置图片的大小*/
.research-item .link img {
    width: 150px;
    margin-right: 40px;
}

/*设置商品信息的间距*/
.research-item .link .information {
    width: 400px;
}

.research-item .link .information > li {
    margin-top: 23px;
}

/*设置价钱的样式*/
.research-item .link .information .price-wrapper .icon-renminbi1688,
.research-item .link .information .price-wrapper .price {
    float: left;
    color: red;
    font-size: 25px;
    font-weight: bold;
}

/*设置卖家信息的样式*/
.research-item .link .information .seller-wrapper .icon-icon_shouhuodizhi,
.research-item .link .information .seller-wrapper .seller {
    float: left;
    font-size: 15px;
}

/*设置商品描述信息的样式*/
.research-item .link .information .describe {
    text-align: left;
    width: 400px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 16px;
}

/*设置商品项目右边箭头的样式*/
.research-item .link .icon-bianji {
    position: absolute;
    display: block;
    color: rgb(68, 78, 88);
    font-size: 40px;
    line-height: 70px;
    width: 70px;
    height: 70px;
    top: 0;
    bottom: 0;
    right: 30px;
    margin: auto;
    transition: color 0.3s ease;
}

.research-item .link .icon-bianji:hover {
    color: #ff6700;
}

.uc-box {
    color: #333;
    padding: 36px 0;
    background-color: rgba(255, 255, 255, 0.8);
    margin-top: 50px;
    .uc-content-box {
        color: #333;
        margin: 0 48px;

        .box-hd:first-child {
            margin-bottom: 30px;
        }

        .box-hd {
            color: #333;

            .title {
                margin: 0;
                font-size: 30px;
                font-weight: 400;
                line-height: 68px;
                color: #757575;
            }

            .more {
                color: #333;
                border-bottom: 0;

                .filter-list {
                    color: #333;
                    float: left;
                    margin: 0;
                    padding: 18px 0;
                    list-style-type: none;
                    font-size: 16px;
                    line-height: 1.25;

                    li {
                        list-style-type: none;
                        font-size: 16px;
                        line-height: 1.25;
                        float: left;
                        padding: 0 20px;
                        border-left: 1px solid #e0e0e0;
                        color: #757575;

                        a {
                            list-style-type: none;
                            font-size: 16px;
                            line-height: 1.25;
                            background-color: rgba(0, 0, 0, 0);
                            text-decoration: none;
                            color: #757575;
                            cursor: pointer;
                        }
                    }

                    .active {
                        a {
                            color: #ff6700;
                        }
                    }

                    .first {
                        list-style-type: none;
                        font-size: 16px;
                        line-height: 1.25;
                        float: left;
                        padding: 0 20px;
                        padding-left: 0;
                        border-left: 0;
                    }
                }

                .search-form {
                    color: #333;
                    float: right;
                    position: relative;
                    width: 262px;
                    height: 40px;
                    margin-top: 8px;

                    label {
                        color: #333;
                        display: none !important;
                    }

                    input[type="search"] {
                        -webkit-text-size-adjust: 100%;
                        font: inherit;
                        margin: 0;
                        -webkit-appearance: textfield;
                        box-sizing: content-box;
                        right: 41px;
                        z-index: 1;
                        width: 189px;
                        height: 42px;
                        padding: 0 15px;
                        font-size: 12px;
                        line-height: 40px;
                        color: #757575;
                        position: absolute;
                        top: 0;
                        border: 1px solid #e0e0e0;
                        outline: 0;
                        transition: all 0.2s;
                    }

                    .search-btn {
                        -webkit-text-size-adjust: 100%;
                        font: inherit;
                        margin: 0;
                        font-family: iconfont !important;
                        font-style: normal;
                        -webkit-font-smoothing: antialiased;
                        -webkit-text-stroke-width: 0.2px;
                        -webkit-appearance: button;
                        cursor: pointer;
                        position: absolute;
                        top: 0;
                        border: 1px solid #e0e0e0;
                        outline: 0;
                        transition: all 0.2s;
                        right: 0;
                        z-index: 2;
                        width: 42px;
                        height: 42px;
                        font-size: 0px;
                        line-height: 42px;
                        background: #fff;
                        color: #616161;

                        vertical-align: middle;
                        text-align: center;

                        .icon-sousuo {
                            font-size: 24px;
                            transition: color 0.3s ease;
                        }

                        .icon-sousuo:hover {
                            color: #ff6700;
                        }
                    }
                }
            }

            div {
                .order-list {
                    color: #333;
                    margin: 0;
                    padding: 10px 0;
                    list-style-type: none;
                }
            }
        }

        .wrapper {
            background-color: white;
            width: 1200px;
            margin: 0 auto;
            padding-bottom: 30px;
        }
    }
}
</style>